package com.dmy.common.utils;

import org.apache.tomcat.util.http.fileupload.IOUtils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;

/**
 * create by YCQ for 2020/1/10 9:40
 */
public class HttpHelper {
    public static final Map<ImplType,HttpHelper> cacheContainer = new ConcurrentHashMap<>();
    private HttpHelper(){}
    public static HttpHelper getInstance(ImplType type){
        return cacheContainer.computeIfAbsent(type,t->new HttpHelper(type));
    }

    private HttpClient client;
    public void get(String url,Consumer<byte[]> fn) throws Exception {
        client.get(url,fn);
    }

    public HttpHelper(ImplType type) {
        switch (type){
            case OKHTTP:
                break;
            case JDK_HTTP:
                this.client = new JDKHttpClient();
                break;
            case HTTPCLIENT:
                break;
        }
    }

    public  enum ImplType{
        OKHTTP,HTTPCLIENT,JDK_HTTP
    }

    public interface HttpClient{
        void get(String url, Consumer<byte[]> resBody)throws Exception;
    }
    public class JDKHttpClient implements HttpClient{
        @Override
        public void get(String url, Consumer<byte[]> resBody) throws Exception{
            URL u = new URL(url);
            HttpURLConnection connection = (HttpURLConnection)u.openConnection();
          try {
              connection.setDoInput(true);
              connection.setDoOutput(false);
              connection.setRequestMethod("GET");
              connection.setReadTimeout(5000);
              connection.setConnectTimeout(5000);
              connection.connect();
              InputStream inputStream = connection.getInputStream();

              ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
              IOUtils.copy(inputStream,byteArrayOutputStream);
              resBody.accept(byteArrayOutputStream.toByteArray());
          }finally {
              connection.disconnect();
          }

        }
    }
}
